﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Experimental.UIElements;
using UnityEngine.UI;
using Button = UnityEngine.UI.Button;
using Image = UnityEngine.UI.Image;

public class FriendItem : MonoBehaviour
{

	public Image avatarImage;

	public Text nick;

	private Button _button;

	private User _user;

	public User User
	{
		get { return _user; }
		set { _user = value; }
	}

	// Use this for initialization
	void Start ()
	{
		_button = this.GetComponent<Button>();
		
		_button.onClick.AddListener(delegate { StartChat(); });
	}
	
	// Update is called once per frame
	void Update () {
		
	}

	/// <summary>
	/// 刷新显示，外部调用
	/// </summary>
	public void SyncShow()
	{
		nick.text = _user.Nick;
		//todo 处理image
		HttpTool.Instance.GetImageConvertToSpriteByURL(_user.Avatar,"opponent");
		StartCoroutine(SetSpriteToImage());

	}

	private void StartChat()
	{
		Debug.Log("开始聊天");
		StartChatRequest request = UnityFacade.Instance.UiManager.InstantiatedPanelDict[PanelType.ChatListPanel].GetComponent<StartChatRequest>();
		request.SendRequest(_user.UserId);


	}
	
	
	private IEnumerator SetSpriteToImage()
	{
		//todo 可以开启一个等待动画的显示
        
		while (HttpTool.Instance.OpponentSprite == null)
		{
			yield return new WaitForFixedUpdate();
		}
		avatarImage.sprite = HttpTool.Instance.OpponentSprite;
		//置为null，待下一次处理
		HttpTool.Instance.ClearSprite("opponent");
       
	}
}
